package com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.ui.ai;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.adapter.ChatMessageAdapter;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.databinding.FragmentAiBinding;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.model.ChatMessage;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.model.UserViewModel;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.GlobalViewModelStore;
import com.example.ai_basedintelligentdiagnosisandtreatmentofchildren.utils.MyApplication;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AiFragment extends Fragment {

    private FragmentAiBinding binding;
    private List<ChatMessage> chatMessages;
    private ChatMessageAdapter adapter;
    private static final String API_KEY = "YOUR_OPENAI_API_KEY";
    private static final String API_URL = "https://api.openai.com/v1/chat/completions";
    private ExecutorService executorService = Executors.newSingleThreadExecutor();
    private Handler handler = new Handler(Looper.getMainLooper());
    private UserViewModel userViewModel;
    private ArrayList<String> aiAnswers = new ArrayList<>();

    @SuppressLint("MissingInflatedId")
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentAiBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        setUserViewModel();
        setAiAnswer();
        setChatRecyclerView();
        setButtons();

        return view;
    }

    private void setUserViewModel(){
        //用户身份
        // 获取全局共享的 UserViewModel
        userViewModel = GlobalViewModelStore
                .getInstance(MyApplication.getInstance())
                .get(UserViewModel.class);
    }

    private void setChatRecyclerView() {
        chatMessages = new ArrayList<>();
        long currentTime = System.currentTimeMillis();
        chatMessages.add(new ChatMessage("请问有什么需要帮助吗？", false, currentTime,"AI"));
        adapter = new ChatMessageAdapter(requireContext(), chatMessages);

        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        binding.chatRecyclerView.setLayoutManager(layoutManager);
        binding.chatRecyclerView.setAdapter(adapter);
    }

    private void setAiAnswer() {
        // 初始化 AI 万能答案
        aiAnswers.add("这是一个常见的问题，你可以尝试...");
        aiAnswers.add("我不太确定，你可以提供更多信息。");
        aiAnswers.add("让我想一想，稍后给你回复。");
        aiAnswers.add("这个问题需要更多的信息才能回答。");
        aiAnswers.add("我需要更多的信息才能回答这个问题。");
        aiAnswers.add("这个问题超出了我的知识范围。");
    }

    private void setButtons() {
        binding.sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String message = binding.messageEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(message)) {
                    long currentTime = System.currentTimeMillis();
                    chatMessages.add(new ChatMessage(message, true, currentTime,"我"));
                    adapter.notifyDataSetChanged();
                    binding.messageEditText.setText("");
                    binding.chatRecyclerView.scrollToPosition(chatMessages.size() - 1);

                    // 添加加载提示消息
                    ChatMessage loadingMessage = new ChatMessage("全力搜索中...", false, currentTime,"AI");
                    chatMessages.add(loadingMessage);
                    adapter.notifyDataSetChanged();
                    binding.chatRecyclerView.scrollToPosition(chatMessages.size() - 1);

                    // 模拟延迟
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            // 移除加载提示消息
                            chatMessages.remove(loadingMessage);
                            // 获取 AI 回答
                            int randomIndex = new Random().nextInt(aiAnswers.size());
                            String aiAnswer = aiAnswers.get(randomIndex);
                            chatMessages.add(new ChatMessage(aiAnswer, false, System.currentTimeMillis(),"AI"));
                            adapter.notifyDataSetChanged();
                            binding.chatRecyclerView.scrollToPosition(chatMessages.size() - 1);
                        }
                    }, 2000); // 延迟 2 秒，可根据需要调整
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 关闭 ExecutorService
        executorService.shutdown();
    }
}